/*
 * Copyright 2011 www.pretty-tools.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#include "stdafx.h"
#include "DOMParser.h"


// CDOMParser

CDOMParser::CDOMParser()
{
    ATLTRACE( _T("CDOMParser::CDOMParser()\n") );
}

CDOMParser::~CDOMParser()
{
    ATLTRACE( _T("CDOMParser::~CDOMParser()\n") );
}

STDMETHODIMP CDOMParser::parseFromStream(VARIANT vtStream, VARIANT charset, VARIANT contentLength, VARIANT contentType, IXMLDOMDocument** pIXMLDOMDocument)
{
    if (vtStream.vt != VT_DISPATCH)
        return E_INVALIDARG;
    if (!pIXMLDOMDocument)
        return E_POINTER;

    IDispatch* stream = vtStream.pdispVal;

    CComPtr<IXMLDOMDocument> document;
    RETURN_FAILED(document.CoCreateInstance(L"Microsoft.XMLDOM"))

    CComQIPtr<IFileInputStream> pFileInputStream(stream);
    if (pFileInputStream)
    {
        ULONGLONG ullPos = 0;
        RETURN_FAILED(pFileInputStream->tell(&ullPos));

        CComQIPtr<ISafeLocalFile> pSafeLocalFile(stream);
        if (ullPos == 0 && pSafeLocalFile)
        {
            CComBSTR bsPath;
            RETURN_FAILED(pSafeLocalFile->GetPath(&bsPath))

            VARIANT vtFileName;
            vtFileName.vt = VT_BSTR;
            vtFileName.bstrVal = bsPath;

            VARIANT_BOOL bSuccess = VARIANT_FALSE;
	        RETURN_FAILED(document->load(vtFileName, &bSuccess))
            RETURN_E_FAIL_ON_FALSE(VARIANT_TRUE == bSuccess);

            *pIXMLDOMDocument = document.Detach();

            return S_OK;
        }
    }

    return E_NOTIMPL;
}

STDMETHODIMP CDOMParser::parseFromString(BSTR str, VARIANT contentType, IXMLDOMDocument** pIXMLDOMDocument)
{
    return E_NOTIMPL;
}
